<template>
  <div>
    <!-- 添加界面 -->
    <el-button
      type="primary"
      @click="addPatentInfo"
      color="#FFB805"
      :disabled="!this.hasAuth('sys:patent:add')"
      >添加</el-button
    >
    <el-dialog
      v-model="dialogFormToAdd"
      title="新增专利"
      top="5vh"
      @close="resetForm('InfoForm')"
    >
      <el-scrollbar height="700px">
        <el-form
          ref="InfoForm"
          :model="InfoForm"
          label-width="120px"
          class="demo-ruleForm"
          :rules="rules"
        >
          <el-form-item label="专利类别" prop="patentType">
            <el-select v-model="InfoForm.patentType" style="width: 100%">
              <el-option
                v-for="item in patentType"
                :key="item.id"
                :label="item.typeName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="专利名称" prop="patentName">
            <el-input v-model="InfoForm.patentName" type="text"></el-input>
          </el-form-item>
          <el-form-item label="专利获得日期" prop="publishDate">
            <el-date-picker
              style="width: 100%"
              v-model="InfoForm.publishDate"
              type="date"
              placeholder="专利获取时间"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="第一单位名称" prop="firstUnit">
            <!-- <el-input v-model="InfoForm.firstUnit" type="text"></el-input> -->
            <el-autocomplete
              v-model="InfoForm.firstUnit"
              :fetch-suggestions="querySearchAsync"
              placeholder="请输入本人所属单位"
              @select="handleSelectFirstUnit"
              value-key="companyName"
              :trigger-on-focus="false"
              style="width:100%"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item label="其他单位" prop="otherUnit">
            <!-- <el-input v-model="InfoForm.otherUnit" type="text"></el-input> -->
            <el-autocomplete
              v-model="InfoForm.otherUnit"
              :fetch-suggestions="querySearchAsync"
              placeholder="请输入本人所属单位"
              @select="handleSelectOtherUnit"
              value-key="companyName"
              :trigger-on-focus="false"
              style="width:100%"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item label="专利人" prop="person">
            <el-input v-model="InfoForm.person" type="text"></el-input>
          </el-form-item>
          <el-form-item label="基金支持号" prop="projectNum">
            <el-input v-model="InfoForm.projectNum" type="text"></el-input>
          </el-form-item>
          <el-form-item label="基金支持项目" prop="projectId">
            <el-select
              v-model="InfoForm.projectId"
              style="width: 100%"
              @change="this.InfoForm.projectName = ''"
            >
              <el-option
                v-for="item in projectList"
                :key="item.projectName"
                :label="item.projectName"
                :value="item.projectName"
              />
              <el-option label="其他项目" value="其他项目" />
            </el-select>
          </el-form-item>
          <el-form-item
            v-show="InfoForm.projectId == '其他项目'"
            label="基金支持项目"
            prop="projectName"
          >
            <el-input
              v-model="InfoForm.projectName"
              placeholder="请输入其他基金支持项目名称"
            />
          </el-form-item>

          <el-form-item label="添加附件" prop="file">
            <el-upload
              class="upload-demo"
              :before-remove="beforeRemove"
              :on-change="fileChangeFunc"
              drag
              action=""
              multiple
              name="file"
              style="float: left"
              :file-list="fileList"
              :auto-upload="false"
            >
              <el-icon class="el-icon--upload"><Document /></el-icon>
              <div class="el-upload__text">
                拖放文件上传 或 <em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  单个文件最大为50MB,总上传大小为100MB
                </div>
              </template>
            </el-upload>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm('InfoForm')"
              >提交</el-button
            >
            <el-button @click="resetForm('InfoForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<script>
import axios from "../../utils/request";
import { ElNotification } from "element-plus";
import { Document } from "@element-plus/icons";
export default {
  name: "PatentInfoAdd",
  props: ["isOpen"],
  inject: ["reload"],
  components: { Document },
  data() {
    return {
      InfoForm: { projectName: "",firstUnitId:-1,otherUnitId:-1},
      dialogFormToAdd: this.isOpen,
      useable: false,
      // 表单校验规则
      rules: {
        patentType: [
          { required: true, message: "该字段不允许为空", trigger: "blur" },
        ],
        patentName: [
          { required: true, message: "该字段不允许为空", trigger: "blur" },
        ],
        publishDate: [
          { required: true, validator:this.checkPublishDate, trigger: "blur" },
        ],
        firstUnit: [
          { required: true, message: "该字段不允许为空", trigger: "blur" },
        ],
        otherUnit: [
          { required: true, message: "该字段不允许为空", trigger: "blur" },
        ],
        person: [
          { required: true, message: "该字段不允许为空", trigger: "blur" },
        ],
        projectNum: [
          { required: true, message: "该字段不允许为空", trigger: "blur" },
        ],
        projectId: [
          { required: true, message: "该字段不允许为空", trigger: "blur" },
        ],
        projectName: [
          { required: true, validator: this.checkProjectName, trigger: "blur" },
        ],
      },
      fileList: [],
      files: [],
      restaurants:[],
      state:''
    };
  },
  methods: {
    /**
     * 表单数据校验规则
     */
    checkProjectName(rule, value, callback) {
      if (this.InfoForm.projectId == "其他项目") {
        if (value == "") {
          callback(new Error("该字段不允许为空"));
        }
      }
      callback();
    },
    checkPublishDate(rule, value, callback) {
      if (value == null || value == "") {
        callback(new Error("该字段不允许为空"));
      } else {
        let nowDate = new Date();
        let publishDate = new Date(value);
        if (publishDate > nowDate) {
          callback(new Error("不允许大于当前时间"));
        } else {
          callback();
        }
      }
    },
    /**
     * 功能函数
     */
    addPatentInfo() {
      this.dialogFormToAdd = true;
    },
    //表单提交
    submitForm(formName) {
      this.$refs.InfoForm.validate((valid) => {
        if (valid) {
          this.InfoForm.enterUserId = this.$store.state.userInfo.userId;
          var formData = new window.FormData();
          formData.append(
            "patentInfo",
            new Blob([JSON.stringify(this.InfoForm)], {
              type: "application/json",
            })
          );
          if (this.files.length != 0) {
            this.files.forEach((data) => {
              formData.append("files", data.raw);
            });
          }
          axios({
            url: "/PatentInfo/add",
            method: "post",
            headers: { "Content-Type": "multipart/form-data" },
            data: formData,
          }).then((res) => {
            if (res.data.status === 200) {
              ElNotification({
                message: res.data.message,
                type: "success",
              });
            }
            this.reload();
          });
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    hasAuth(perm) {
      var authority = this.$store.state.menus.permList;
      return authority.indexOf(perm) > -1;
    },
    getPatentType() {
      axios.get("/patentTypeList").then((res) => {
        this.patentType = res.data.data.patentType;
      });
    },
    // 表单文件上传函数
    beforeRemove(file, fileList) {
      console.log(fileList);
      var re = this.$confirm(`是否删除文件 ${file.name} ?`)
        .then(() => {
          this.files.splice(this.files.indexOf(file), 1);
        })
        .catch(() => {
          return false;
        });
      return re;
    },
    fileChangeFunc(file, fileList) {
      this.files.push(file);
    },
    //获取项目列表
    getProjectList() {
      axios.get("/ProjectInfo/projectList").then((res) => {
        this.projectList = res.data.data.projectList;
      });
    },
    /**
     * 单位信息输入建议
     */
    //获取单位信息
    getCompanyInfo() {
      axios.get("/CompanyInfos/searchInput").then((res) => {
        // console.log(res);
        this.restaurants = res.data.data.map_companyInfo;
      });
    },
    querySearchAsync(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createStateFilter(queryString))
        : restaurants;
      cb(results);
    },
    createStateFilter(queryString) {
      return (state) => {
        return (
          state.companyName.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    handleSelectFirstUnit(item) {
      this.InfoForm.firstUnitId = item.id;
    },
    handleSelectOtherUnit(item){
      this.InfoForm.otherUnitId = item.id;
    }
  },
  mounted() {
    this.getPatentType();
    this.getProjectList();
    this.getCompanyInfo();
  },
};
</script>
